package cn.chencaiju.day10;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.junit.Test;

public class RandomAccessFileTest {
	String file="C:\\Users\\haiming\\Pictures\\lizhi.jpg";
	String target="C:\\Users\\haiming\\Pictures\\lizhi2.jpg";
	
	@Test public void testCopyRemain() {
		CopyFile(new File(file),new File(target));
//		copyRemain(file,target);
	}
	
	/**
	 * 断点续传
	 * @param source
	 * @param target
	 */
	public void copyRemain(String source,String target) {
		File targetFile=new File(target);
		try(
			RandomAccessFile raf=new RandomAccessFile(source, "r");
			FileOutputStream fo=new FileOutputStream(target,true);
			){
			long size=targetFile.length();
			raf.seek(size);
			int count=0;
			byte[] chars=new byte[1024];
			while((count=raf.read(chars))!=-1) {
				fo.write(chars, 0, count);
			}
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 传输文件中断
	 * @param source
	 * @param target
	 */
	public static void CopyFile(File source,File target) {
		try (	FileInputStream fi=new FileInputStream(source);
				FileOutputStream fo=new FileOutputStream(target);
			){
			// 文件大小
			long size = source.length();

			// 取到一个随机的位置
			long ran = (long) (Math.random() * size);
			
			long sum=0;
			int count=0;
			byte[] contents = new byte[1024];
			while ((count= fi.read(contents))!=-1) {
				sum+=count;
				if(sum>=ran)break;
				fo.write(contents,0, count);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
}
